package com.sunday.aomicaichang.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.MallAdapter;
import com.sunday.aomicaichang.constValues.ConstValue;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.model.Product;
import com.sunday.aomicaichang.model.Score;
import com.sunday.aomicaichang.ui.common.WebViewActivity;
import com.sunday.aomicaichang.ui.my.MyIntegralActivity;
import com.sunday.member.utils.SignUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/1.
 */

public class MallActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.rule)
    ImageView rule;
    @Bind(R.id.score)
    TextView score;
    @Bind(R.id.ly_record)
    LinearLayout lyRecord;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    private int pageSize = 20;
    private int pageNumber = 1;
    private GridLayoutManager layoutManager;
    private MallAdapter mallAdapter;
    private List<Product> productList;
    private BigDecimal totalScore;
    public int footerState = 0; //0,正在加载 1,没有更多
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mall);
        ButterKnife.bind(this);
        layoutManager = new GridLayoutManager(mContext,2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        mallAdapter = new MallAdapter(mContext);
        recyclerView.setAdapter(mallAdapter);
        recyclerView.addOnScrollListener(mOnScrollListener);
        if (productList == null) {
            productList = new ArrayList<>();
        }
        getData();
        getDataScore();
    }
    private void getDataScore(){
        String nonce = MD5Utils.random();
        String size = String.valueOf(pageSize);
        String number = String.valueOf(pageNumber);
        String[] str1 = new String[]{"type", "pageSize", "pageNumber", "nonce"};
        String[] str2 = new String[]{"1", size, number, nonce};
        showLoadingDialog(0);
        Call<ResultDO<Score>> call = ApiClient.getApiAdapter().getScore(1, pageSize, pageNumber,
                nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<Score>>() {
            @Override
            public void onResponse(Call<ResultDO<Score>> call, Response<ResultDO<Score>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<Score> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    totalScore=resultDO.getResult().getTotalScore();
                    score.setText(totalScore + "");
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Score>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {

        private int lastVisibleItem;

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = layoutManager.findLastVisibleItemPosition();
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == mallAdapter.getItemCount()
                    && getFooterState() == 0) {
                //加载更多
                pageNumber++;
                getData();
            }
        }
    };
    public int getFooterState() {
        return footerState;
    }
    public void setFooterState(int footerState) {
        this.footerState = footerState;
    }

    @OnClick({R.id.rule, R.id.ly_record,R.id.ly_integral})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.rule:
                intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra("url", ApiClient.API_URL1+"sunday/mobile/advertisement/html5ByZoneCode?zoneKey=score_rule" );
                intent.putExtra("title","兑换规则");
                startActivity(intent);
                break;
            case R.id.ly_record:
                intent = new Intent(mContext, MallRechangeRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.ly_integral:
                intent = new Intent(mContext, MyIntegralActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void getData() {
        String nonce = MD5Utils.random();
        String size = String.valueOf(pageSize);
        String number = String.valueOf(pageNumber);
        int villageId= SharePerferenceUtils.getIns(mContext).getInt(ConstValue.AREA,0);
        String[] str1 = new String[]{"type", "villageId","pageSize", "pageNumber", "nonce"};
        String[] str2 = new String[]{"2",String.valueOf(villageId), size, number, nonce};
        if(pageNumber==1)
        showLoadingDialog(0);
        Call<ResultDO<List<Product>>> call = ApiClient.getApiAdapter().product(2,villageId, pageSize, pageNumber,
                nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<Product>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Product>>> call, Response<ResultDO<List<Product>>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<List<Product>> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    List<Product> products = resultDO.getResult();
                    if (pageNumber == 1)
                        productList.clear();
                    productList.addAll(products);
                    if (products.size() >= 0 && products.size() < pageSize ) {
                        setFooterState(1);
                    } else {
                        setFooterState(0);
                    }
                    mallAdapter.setmData(productList);
                    mallAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Product>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }
}
